<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Category as CategoryModel;
use fast\Tree;
use think\Db;

/**
 * 分类管理
 *
 * @icon   fa fa-list
 * @remark 用于统一管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Article extends Backend
{

    /**
     * @var \app\common\model\Category
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Article');
        //$categorys = collection(model('Category')->select())->toArray();
        //$this->assign('categorys',$categorys);

        $categorys = Db('Category')
            ->alias('c')
            ->join('activetype a','c.activetype_id=a.id','left')
            ->field(['c.*','a.name as aname'])
            ->select();
        foreach($categorys as $mk=>$my){
            $categorys[$mk]['name'] = '【'.$my['aname'].'】'."&nbsp;&nbsp;".$my['name'];
        }
        $this->assign('categorys',$categorys);



        $activetypes = collection(model('Activetype')->where(['status'=>'normal'])->select())->toArray();


        /*
        $newdata = array();
        foreach($activetypes as $ck=>$cv){
           $category =  Db('Category')->where(['activetype_id'=>$cv['id']])->select();
           if($category){
               foreach ($category as $kk=>$vv){
                   $activetypes[$ck]['son'][$kk]['id'] = $vv['id'];
                   $activetypes[$ck]['son'][$kk]['name'] = $vv['name'];
               }
           }else{
               $activetypes[$ck]['son'] = array();
           }


        }
        */



        $this->assign('activetypes',$activetypes);


    }



    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = Db('Article')
                ->alias('a')
                ->join('category c','a.category_id=c.id','left')
                ->join('activetype b','b.id=c.activetype_id','left')
                ->where($where)
                ->field(['a.*','c.name as cname','c.id as cid','c.activetype_id','b.id as bid','b.name as bname'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();


            /*
            foreach($list as $bk=>$bv){
                $list[$bk]['cname'] = '【'.$bv['bname'].'】'.$bv['cname'];
            }
            */



            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

    public function demo()
    {
        $id = $this->request->post("id");
        $res = array();
        $categorys  = Db('category')
            ->where(['activetype_id'=>$id,'status'=>'normal'])->field('id,name')->select();
        echo json_encode($categorys);
    }
    public function activetype()
    {

        $where = ['status' => 'normal'];
        $activetypelist = null;

        $activetypelist = Db::name('activetype')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
        $this->success('', null, $activetypelist);

    }
    public function category()
    {
        $activetype_id = $this->request->get('activetype_id');
        $where = ['status' => 'normal'];
        $categorylist = null;
        if ($activetype_id !== '') {

            if ($activetype_id) {
                $where['activetype_id'] = $activetype_id;
            }

            $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
        }
        $this->success('', null, $categorylist);
    }
}
